<template>
  <v-container fluid>
    <v-row>
      <v-col cols="12">
        <v-form ref="postAddForm" v-model="valid" lazy-validation>
          <!--标题-->
          <v-text-field v-model="title" :rules="titleRules" outlined label="标题" clearable></v-text-field>
          <!--摘要-->
          <v-text-field v-model="desc" :rules="descRules" outlined label="摘要" clearable></v-text-field>
          <div id="editor">
            <span>【请输入正文，不少于１５个字符。】</span>
          </div>
          <br/>
          <!--提交按钮-->
          <v-btn :disabled="!valid" color="primary" class="mr-4" v-on:click="validate">提交</v-btn>
          <!--清空按钮-->
          <v-btn color="default" class="mr-4" @click="editor.txt.clear()">清空</v-btn>
        </v-form>
      </v-col>
    </v-row>
  </v-container>
</template>

<script>
import E from 'wangeditor'

export default {
  name: 'PostAdd',
  data: () => ({
    editor: null,
    valid: true,
    title: '',
    titleRules: [
      v => !!v || '请输入标题',
      v => (v.length >= 1 && v.length <= 20) || '标题不得超过40个字符'
    ],
    desc: '',
    descRules: [
      v => !!v || '请输入摘要',
      v => (v.length >= 1 && v.length <= 50) || '摘要不得超过100个字符'
    ]
  }),
  methods: {
    validate () {
      const valid = this.$refs.postAddForm.validate()
      if (valid) {
        this.$axios.post('api/post/', {
          title: this.title,
          desc: this.desc,
          content: this.editor.txt.html(),
          owner: this.$store.state.user.username
        }).then(response => {
          console.log(response)
          // 提交成功以后返回帖子管理界面
          this.$router.push({
            name: 'PostManage',
            id: this.$store.state.user.id
          })
        }).catch(error => {
          console.log(error)
        })
      }
    }
  },
  mounted () {
    this.editor = new E('#editor')
    // 启用本地图片上传
    this.editor.customConfig.uploadImgShowBase64 = true
    this.editor.create()
  }
}
</script>

<style scoped>

</style>
